import { _decorator, Component, director, DynamicAtlasManager, Label, macro, Node, ProgressBar, SpriteAtlas, SpriteFrame, Prefab, AudioClip } from 'cc';
import { AudioManager, Core } from './Core/Core';
import { EGameMode, EPet, EScene } from './Config/Enum';
import { ResourceManager } from './Core/ResourceManager';
import { Util } from './Util';
import { sceneRes } from './Config/ResourceConfig';

const { ccclass, property } = _decorator;

// 保持原有的宏配置
macro.CLEANUP_IMAGE_CACHE = false;
DynamicAtlasManager.instance.enabled = true;

@ccclass('Start')
export class Start extends Component {

    // 推荐在编辑器中绑定这些节点，性能更好
    @property(Node) ndFirstPage: Node = null!;
    @property(Node) ndSecondPage: Node = null!;
    @property(Node) ndChoosePage: Node = null!;
    
    @property(ProgressBar) progressBar: ProgressBar = null!;
    @property(ProgressBar) progressBar2: ProgressBar = null!;

    protected onLoad() {
        console.log("Start onLoad");

        // 1. 初始化核心单例
        Core.Instance.init();
        
        // 2. 播放 BGM
        AudioManager.Instance.playMusic("start_bgm");
        
        // 3. 节点绑定兜底 (如果在编辑器没拖拽，尝试代码查找)
        this.bindNodes();

        // 4. 初始化 UI 状态
        if (this.progressBar) this.progressBar.progress = 0;
        if (this.progressBar2) this.progressBar2.progress = 0;
        
        this.ndFirstPage.active = true;
        this.ndSecondPage.active = false;
        this.ndChoosePage.active = false;
    }

    private bindNodes() {
        if (!this.ndFirstPage) this.ndFirstPage = this.node.getChildByName('FirstPage');
        if (!this.ndSecondPage) this.ndSecondPage = this.node.getChildByName('SecondPage');
        if (!this.ndChoosePage) this.ndChoosePage = this.node.getChildByName('FirstChoosePage');
        
        if (!this.progressBar && this.ndFirstPage) {
            this.progressBar = this.ndFirstPage.getChildByName('ProgressBar').getComponent(ProgressBar);
        }
        if (!this.progressBar2 && this.ndChoosePage) {
            this.progressBar2 = this.ndChoosePage.getChildByName('ProgressBar').getComponent(ProgressBar);
        }
    }

    protected async onEnable() {
        this.ndSecondPage.on(Node.EventType.TOUCH_END, this.onButtonCloseWindow, this);

        // 1. 优先加载 Start 场景自身需要的资源 (如图集)
        await this.loadAssetsWithProgress(sceneRes[EScene.Start], this.progressBar);

        // 2. 根据玩家状态分流
        if (!Core.Instance.isNewPlayer) {
            this.handleOldPlayer();
        } else {
            this.handleNewPlayer();
        }
    }

    protected onDisable(): void {
        this.ndSecondPage.off(Node.EventType.TOUCH_END, this.onButtonCloseWindow, this);
    }

    // ====================== 流程处理 ======================

    /** 老玩家流程：加载 Main 资源 -> 跳转 Main */
    private async handleOldPlayer() {
        console.log("老玩家，开始加载 Main 场景资源...");
        
        // 重置进度条准备加载 Main 资源
        this.progressBar.progress = 0;
        
        await this.loadAssetsWithProgress(sceneRes[EScene.Main], this.progressBar);

        console.log("Main 资源加载完毕，进入游戏");
        director.loadScene(EScene.Main);
    }

    /** 新玩家流程：显示剧情/选人 -> 后台加载 Battle -> 等待点击开始 */
    private async handleNewPlayer() {
        console.log("新玩家，进入引导流程...");

        // 切换 UI
        this.ndFirstPage.active = false;
        this.ndChoosePage.active = true;
        this.ndSecondPage.active = true; // 剧情页

        // 开始加载首战资源
        // 注意：这里不需要 await，让它在后台加载，不阻塞 UI 交互
        this.loadFirstBattleAssets();
    }

    private async loadFirstBattleAssets() {
        if (!this.progressBar2) return;
        
        this.progressBar2.progress = 0;
        
        // 异步加载战斗资源
        await this.loadAssetsWithProgress(sceneRes[EScene.FirstBattle], this.progressBar2);

        // 加载完成
        this.progressBar2.progress = 1.0;
        const label = this.progressBar2.node.parent?.getChildByName('Label');
        if(label) label.getComponent(Label).string = "战阵布置完成";
        
        // 标记战斗场景资源已就绪
        Core.Instance.loadedScene.add(EScene.Battle);

        // 可选：闲时预加载 Main 场景资源 (低优先级)
        // Core.Instance.startBackgroundPreload_assetList(sceneRes[EScene.Main]);
    }

    // ====================== 通用资源加载 (并行优化版) ======================

    /**
     * 通用资源加载器，支持并行加载和进度回调
     */
    private async loadAssetsWithProgress(assets: string[], progressBar: ProgressBar) {
        if (!assets || assets.length === 0) {
            if (progressBar) progressBar.progress = 1.0;
            return;
        }

        const total = assets.length;
        let loadedCount = 0;

        // 创建所有加载任务的 Promise 数组
        const promises = assets.map(async (path) => {
            // 简单的类型推断
            let type: any = SpriteFrame; 
            if (path.endsWith("AutoAtlas")) {
                type = SpriteAtlas; 
                console.log("图集加载排查 path.endsWithAutoAtlas",path);
            }
            else if (path.includes("prefab")) type = Prefab;
            else if (path.includes("audio")) type = AudioClip;

            try {
                await ResourceManager.Instance.loadRes(path, type);
            } catch (err) {
                console.warn(`[Start] 资源加载跳过: ${path}`, err);
            } finally {
                loadedCount++;
                // 更新进度条
                if (progressBar) {
                    progressBar.progress = loadedCount / total;
                }
            }
        });

        // 并行执行所有加载任务
        await Promise.all(promises);
    }

    // ====================== UI 事件 ======================

    onBtnGoChoosePage() {
        this.ndFirstPage.active = false;
        this.ndChoosePage.active = true;
    }
    
    onButtonCloseWindow(){
        this.ndSecondPage.active = false;
    }

    onButtonStartGame() {
        if (Core.Instance.loadedScene.has(EScene.Battle)) {
            this.initNewGameData();
            // 在切换前可以停止 BGM，或者由 BattleManager 接管
            AudioManager.Instance.stopMusic();
            director.loadScene(EScene.Battle);
        } else {
            Core.Instance.showTips("战阵布置中，请将军少待", this.node);
        }
    }

/** 初始化新游戏数据 */
    private initNewGameData() {
        Core.Instance.currentMode = EGameMode.Normal;
        Core.Instance.currentStage = 1;
        
        // 重置各模式最大关隘
        Util.getObjectValues(EGameMode).forEach(mode => {
            Core.Instance.modeMaxStage[mode] = 1;
        });

        // 初始化玩家与宠物
        Core.Instance.selectedPlayers.clear();
        Core.Instance.selectedPlayers.add(Core.Instance.currentPlayer);
        
        // 【修改点 1】使用 indexOf 代替 includes
        // 如果 indexOf 返回 -1，说明数组中不存在该元素
        if (Core.Instance.unlockedPlayers.indexOf(Core.Instance.currentPlayer) === -1) {
            Core.Instance.unlockedPlayers.push(Core.Instance.currentPlayer);
        }
        
        // 【修改点 2】使用 indexOf 代替 includes
        if (Core.Instance.unlockedPets.indexOf(EPet.Pig) === -1) {
            Core.Instance.unlockedPets.push(EPet.Pig);
        }
        
        Core.Instance.playerLockSet.delete(Core.Instance.currentPlayer);
        Core.Instance.lastSelectedPlayers = Array.from(Core.Instance.selectedPlayers);
        
        // 保存初始状态
        Core.Instance.save();
    }
}